<?php

// +----------------------------------------------------------------------

namespace app\user\home;

use app\common\controller\BaseController;
use aliutil\Auth;
use util\Wxsdk;
use think\Db;

/**
 * 用户授权控制器
 * 获取用户user_id || openid
 * @package app\user\home
 */
class Login extends BaseController
{
	// 支付宝授权
	public function alipay()
	{
		// 授权信息
		$auth = session('user_auth');
		if (!$auth){
			$auth_code = request()->param('auth_code');
			if (!$auth_code) { // 获取auth_code
				// 缓存调整路径
				if (!cookie('?__backurl__')) cookie('__backurl__', url('user/member/index'));
				$url = real_url('user/login/alipay');
				$auth_url = sprintf(config('alipay.auth'), config('alipay.appid'), 'auth_base', $url);
				return redirect($auth_url);
			} else { // 通过auth_code换取userid
				$auth = new Auth;
				$user = $auth->getuserid($auth_code);
				if (isset($user->user_id)){
					session('user_auth', $user->user_id);
				} else {
					$this->error('授权登录失败');
				}
				return redirect(cookie('__backurl__'));
			}
		} else {
			return redirect(cookie('__backurl__'));
		}
	}
	
	// 微信授权
	public function wechat()
	{
		// 授权信息
		$auth = session('user_auth');
		// 缓存调整路径
		if (!cookie('?__backurl__')) cookie('__backurl__', url('user/member/index'));
		
		if (!$auth){
			$auth_code = request()->param('code');
			if (!$auth_code) { // 获取auth_code
				$url = real_url('user/login/wechat');
				$url = urlencode($url);
				$api = 'https://zzpay.zzmind.com/api/wechat/code?url='.$url;
				return redirect($api);
				
			} else { // 通过auth_code换取userid
				//换取TOKEN
				$api = 'https://api.weixin.qq.com/sns/oauth2/access_token?appid='.config('wechat.appid').'&secret='.config('wechat.appsecret').'&code='.$auth_code.'&grant_type=authorization_code';
				$get_token = json_decode(post_curls($api, []), true);
				if (isset($get_token['openid'])){
					session('user_auth', $get_token['openid']);
				} else {
					$this->error('授权登录失败');
				}
				return redirect(cookie('__backurl__'));
			}
		} else {
			return redirect(cookie('__backurl__'));
		}
	}
}
